package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    String prefix;

    @Autowired
    ApArticleMapper articleMapper;

    @Autowired
    AuthorMapper authorMapper;

    /**
     * 生成静态页业务实现
     *
     * @param content   文章内容
     * @param apArticle article对象
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        //获取模板对象
        try {
            Template template = configuration.getTemplate("article.ftl");
            //准备替换模板的数据
            Map map = new HashMap<>();
            map.put("article", apArticle);
            //根据作者id查询作者信息
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            if (apAuthor == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
            }
            map.put("authorApUserId", apAuthor.getUserId());
            map.put("content", JSON.parseArray(content, Map.class));
            //替换模板 并输出到指定地方
            StringWriter stringWriter = new StringWriter();

            template.process(map, stringWriter);
            //上传到minio上 得到的路径修改article  static_url数据
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String path = fileStorageService.store(prefix,
                    apArticle.getId() + ".html", "text/html", inputStream);
            apArticle.setStaticUrl(path);
            //修改article
            int count = articleMapper.updateById(apArticle);
            //打印看下结果
            System.out.println("修改影响的行数: " + count);
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "页面静态化失败 原因: 未找到模板");
        } catch (TemplateException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "页面静态化失败 原因: 替换模板失败");
        }
    }
}